package com.demomaster.quickcompat.widget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.TextView;

import com.demomaster.quickcompat.util.DisplayUtil;

import java.util.Arrays;
import java.util.List;

/**
 * 滚动文字
 */
public class MarqueeTextView extends androidx.appcompat.widget.AppCompatTextView {

    private static final String TAG = "MarqueeTextView" ;
    boolean defStyle = false;//系统默认跑马灯效果

    public MarqueeTextView(Context context) {
        this(context, null);
    }

    public MarqueeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (defStyle) {
            //设置单行
            setSingleLine();
            //设置Ellipsize
            setEllipsize(TextUtils.TruncateAt.MARQUEE);
            //获取焦点
            setFocusable(true);
            //走马灯的重复次数，-1代表无限重复
            setMarqueeRepeatLimit(-1);
            //强制获得焦点
            setFocusableInTouchMode(true);
            requestFocus();
        }
        setSelected(true);
        setHorizontallyScrolling(true);
        //setEllipsize(TextUtils.TruncateAt.MARQUEE);

    }

    /*
     *这个属性这个View得到焦点,在这里我们设置为true,这个View就永远是有焦点的
     */
    @Override
    public boolean isFocused() {
        //QDLogger.println("isFocused");
        if (defStyle) {
            return true;
        } else {
            return super.isFocused();
        }
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction,
                                  Rect previouslyFocusedRect) {
        if (focused) {
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
        }
    }

    @Override
    public void onWindowFocusChanged(boolean focused) {
        if (focused) {
            super.onWindowFocusChanged(focused);
        }
    }

    int mScrollHeight;
    float textWidth;
    float mScrollWidth;


    float viewWidth = 0;

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //mScrollHeight = getMeasuredHeight();
        Log.i(TAG,"onSizeChanged=" + w + ",getMeasuredWidth=" + getMeasuredWidth());

        if (w != viewWidth) {
            viewWidth = w;
            startAnimation();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (isHorizontallyScroll()) {
            if(isMarqueeScroll) {
                String textStr = TextUtils.isEmpty(getText()) ? "" : getText().toString();
                //canvas.save();
                canvas.translate(translate_X, 0);
                //super.onDraw(canvas);
                //canvas.restore();
                Paint paint = getPaint();
                paint.setColor(Color.WHITE);
                canvas.drawText(textStr, 0, paint.getTextSize(), paint); // 绘制文本
                //super.onDraw(canvas);
                canvas.translate(mScrollWidth, 0);
                canvas.drawText(textStr, 0, paint.getTextSize(), paint); // 绘制文本
                //canvas.drawText(textStr, translate_X, 0, getPaint()); // 绘制文本
                //super.onDraw(canvas);
                //canvas.restore();
            }else {
                super.onDraw(canvas);
            }
        } else {
            canvas.translate(0, translate_Y);
            super.onDraw(canvas);
        }
    }

    private boolean isHorizontallyScroll() {
        return true;
    }

    /***设置纵向滚动***/
    int lineIndex;//当前行数
    int translate_Y;//绘制偏移量
    int translate_X;
    List<String> stringlist;
    Handler handler = new Handler();

    public void setTextArray(String[] textArray) {
        this.stringlist = Arrays.asList(textArray);
        lineIndex = 0;
        startAnimation();
    }

    ValueAnimator animator;

    boolean isMarqueeScroll;
    public void startAnimation() {
        if (isHorizontallyScroll()) {
            if(TextUtils.isEmpty(textContent)){
                textWidth = 0;
            }else {
                Paint paint = getPaint();
                textWidth = paint.measureText(textContent);
            }
            Log.i(TAG,"textWidth:" + textWidth + " getMeasuredWidth:" + viewWidth + " getPaddingStart:" + getPaddingStart() + " getPaddingEnd:" + getPaddingEnd());
            if (textWidth <= viewWidth - getPaddingStart() - getPaddingEnd()) {
                isMarqueeScroll = false;
                if (animator != null) {
                    Log.i(TAG,"移除动画");
                    animator.removeAllListeners();
                    animator.removeAllUpdateListeners();
                    animator.cancel();
                    animator = null;
                    translate_X = 0;
                }
                postInvalidate();
                return;
            }
            isMarqueeScroll = true;
            float scrollWidth1 = Math.max(getMeasuredWidth(), textWidth + getPaddingStart() + getPaddingEnd() + DisplayUtil.dip2px(getContext(), 50)); // 计算文本宽度
            if (mScrollWidth != scrollWidth1) {
                this.mScrollWidth = scrollWidth1;
                if (animator != null) {
                    animator.cancel();
                    animator.removeAllUpdateListeners();
                    animator = null;
                }
            }
            animator = ValueAnimator.ofInt(0, (int) -mScrollWidth);
            animator.setDuration(10000);
            animator.setInterpolator(new LinearInterpolator());
            //animator.setRepeatMode(ValueAnimator.RESTART);
            animator.setRepeatCount(-1);
        } else {
            if (stringlist != null) {
                lineIndex = lineIndex % stringlist.size();
                setText(stringlist.get(lineIndex));
            }
            animator = ValueAnimator.ofInt(0, mScrollHeight);
            animator.setDuration(360);
            animator.setInterpolator(new AccelerateInterpolator());
            animator.setRepeatCount(0);
        }
        animator.addUpdateListener(animation -> {
            int value = (int) animation.getAnimatedValue();
            translate_Y = value;
            translate_X = value;
            //QDLogger.d( "progress=" + value);
            //setText(stringlist.get(lineIndex));
            invalidate();
            if (!isHorizontallyScroll()) {
                if (value == mScrollHeight) {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            lineIndex++;
                            startAnimation();
                        }
                    }, 6000);
                }
            }
        });
        //animator.setRepeatMode(ValueAnimator.RESTART);
        //animator.setRepeatCount(0);
        //new AccelerateInterpolator()
        //animator.setInterpolator(new CycleInterpolator());
        animator.start();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        hasAttached = false;
        if (animator != null) {
            animator.cancel();
            animator.removeAllUpdateListeners();
        }
    }

    String textContent;

    @Override
    public void setText(CharSequence text, BufferType type) {
        String textStr = text == null ? "" : text.toString();
        Paint paint = getPaint();
        textWidth = paint.measureText(textStr);
        if (!textStr.equals(textContent)){
            textContent = textStr;
            startAnimation();
        }
        super.setText(text, type);
    }

    @Override
    public void setTextSize(float size) {
        super.setTextSize(size);
        startAnimation();
    }


    @Override
    public void requestLayout() {
        if (hasAttached) {
            super.requestLayout();
            //QDLogger.println("requestLayout");
        }
    }

    boolean hasAttached;

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        hasAttached = true;
        startAnimation();
    }


}
